package com.easylinkin.linkappapi.personality.controller;


import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.easylinkin.linkappapi.facerecognition.dto.OSSPolicy;
import com.easylinkin.linkappapi.facerecognition.service.oss.ObjectStorageOutsideService;
import com.easylinkin.linkappapi.personality.constant.PersonalityConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import java.util.Date;

/**
 * <p>
 * 应用管理表 前端控制器
 * </p>
 *
 * @author XuGuoQing
 * @since 2020-05-19
 */
@RestController
@RequestMapping("/upload")
public class UpLoadController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UpLoadController.class);

    @Value("${oss.accessKeyId}")
    private String accessId;
    @Value("${oss.dir}")
    private String dir;
    @Value("${oss.readHost}")
    private String readHost;

    @Value(("${oss.type}"))
    private String ossType;

    @Value("${oss.bucket}")
    private String bucket;


//    @Autowired
//    private OSSClient ossClient;

    @Autowired
    @Qualifier("oss")
    private ObjectStorageOutsideService minioClient;

    @GetMapping("/policyByType")
    protected RestMessage getUploadPolicyByType(@RequestParam(name = "type") Integer type) {
        //如果是ali云
        if ("minio".equalsIgnoreCase(ossType)) {
            return getUploadPolicyByTypeForMinIo();
        }
        PersonalityConstant.FileTypeEnum fileTypeEnum = PersonalityConstant.FileTypeEnum.valueOf(type);
        String   path = dir+ (fileTypeEnum==null?"default/":fileTypeEnum.getPath());
        OSSPolicy ossPolicy = null;
        try {
            long expireTime = 30 * 60;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, path);
            ossPolicy = minioClient.generatePostPolicy(path);
//            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
//            byte[] binaryData = postPolicy.getBytes("utf-8");
//            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
//            String postSignature = ossClient.calculatePostSignature(postPolicy);
//            Map<String, Object> respMap = new LinkedHashMap<String, Object>();
//            respMap.put("accessId", accessId);
//            respMap.put("policy", encodedPolicy);
//            respMap.put("signature", postSignature);
//            respMap.put("path", path);
//            respMap.put("uploadHost", host);
//            respMap.put("accessHost", readHost);
//            respMap.put("ossType","ali");
//            ja1 = new JSONObject(respMap);
        } catch (Exception e) {
            LOGGER.error("Failed to  get  policy! " ,e);
            return RestBuilders.failureMessage().setMessage("Failed to get   policy !");
        }
        return RestBuilders.successBuilder().data(ossPolicy).build();
    }


    private RestMessage getUploadPolicyByTypeForMinIo() {
        try {
            OSSPolicy respMap = minioClient.generatePostPolicy(dir);
            if ("minio".equals(ossType)) {
                respMap.setPolicy(ossType);
//                respMap.setAccessHost(readHost+respMap.getAccessHost());
//                respMap.setAccessHost(readHost+"/"+bucket);
                respMap.setAccessHost(readHost);
            }
            return RestBuilders.successBuilder().data(respMap).build();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return RestBuilders.failureBuilder().message("get upload policy error").build();
    }
}
